package com.readword.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.POIXMLException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

//import com.alibaba.fastjson2.JSON;
import com.readword.entity.Examination;
import com.readword.util.Cons;
import com.readword.util.HtmlUtil;
import com.readword.util.ItextPdfUtil;
//import com.readword.util.PdfUtil;
import com.readword.util.TextParserUtil;
import com.readword.util.WordUtil;

/**
* @ClassName: IndexController
* @Description: 业务控制器
* @author 码农小鹿
* @date 2024年1月10日 下午1:43:23
*
 */
@RestController
public class IndexController {
	private final static Logger logger = LoggerFactory.getLogger(IndexController.class);

	@PostMapping(value = "/upload")
	public List<Examination> upload(
			@RequestParam("file") MultipartFile file,
			@RequestParam("title") String title) {
		List<Examination> list = getData(file);
		if(null == list || list.size() == 0) {
			logger.info("没有任何解析结果");
			return list;
		}
		return list;
	}

	@PostMapping(value = "/expert")
	public String expert(HttpServletResponse response, 
			@RequestParam("file") MultipartFile file,
			@RequestParam("title") String title) {
		List<Examination> list = getData(file);
		if(null == list || list.size() == 0) {
			return "没有任何解析结果";
		}
		String pdfName = Cons.TOOLS.getRandom() + ".pdf";
		try {
			ItextPdfUtil.htmlToPdf(new HtmlUtil(title, list).outHtml(), pdfName);
			return Cons.FILE.SHOWFILE + pdfName;
		} catch (Exception e) {
			logger.error("html 转pdf异常：{}", e);
			return "创建pdf异常";
		}
	}
	
	
	/**
	 * 在线预览图片
	 * @param response
	 * @param name
	 */
	@GetMapping(value = "/file")
	public void file(HttpServletResponse response, String name) {
        ServletOutputStream outputStream = null;
        BufferedInputStream bufferedInputStream = null;
        try {
        	File file = new File(Cons.FILE.SAVEFOLDER + name);
            outputStream = response.getOutputStream();
            response.addHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(name, "UTF-8"));
            response.addHeader("Content-Length", "" + file.length());
            bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
            byte[] bytes = new byte[1024 * 1024];
            int b = 0;
            while ((b = bufferedInputStream.read(bytes)) != -1) {
                outputStream.write(bytes);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bufferedInputStream.close();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
	}
	
	private List<Examination> getData(MultipartFile file){
		InputStream io = null;
		List<Examination> list = new ArrayList<Examination>();
		try {
			io = file.getInputStream();
		} catch (Exception e) {
			logger.error("获取上传文件异常：{}" , e);
			return list;
		}
		WordUtil word = null;
		try {
			word = new WordUtil(io);
		} catch (POIXMLException e) {
			logger.error("读取文件异常：{}" , e);
			return list;
		} catch (IOException e) {
			logger.error("读取文件异常：{}" , e);
			return list;
		}
		String text = word.read();
		if("".equals(text) || null == text) {
			logger.info("读取word文件内容为空");
			return list;
		}
		list = TextParserUtil.getContent(text);
		return list;
	}
}
